import axios from "axios";
import qs from "qs";
import logger from "./logger";

const baseUrl = "";

const http = axios.create({
  baseUrl,
  timeout: 30000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  },
});

http.interceptors.request.use(
  (config) => {
    logger.request(config);
    if (config.method.toUpperCase() === "POST") {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  (response) => {
    if (response.data.success) {
      logger.success(response);
      return response.data;
    } else {
      logger.warn(response);
      // 看后端错误信息返回在哪里，或者是response.data.msg
      throw Error(response.data.data);
    }
  },
  (error) => {
    logger.error(error.response);
    return Promise.reject(error);
  }
);

export default http;
